package com.gaogzhen.datastructure.linear;

import java.io.Serializable;
import java.util.*;
import java.util.function.Consumer;

/**
 * @author Administrator
 * @version 1.0
 * @description 顺序表
 * @date 2022-10-02 22:05
 */
public class SequenceList<E> implements Serializable {

    /**
     * 默认的初始化容量
     */
    private static final int DEFAULT_CAPACITY = 10;

    /**
     * 空顺序表实例
     */
    private static final Object[] EMPTY_ELEMENTDATA = {};

    /**
     * 默认的空顺序表实例，区别于EMPTY_ELEMENTDATA，用于第一次添加元素
     */
    private static final Object[] DEFAULTCAPACITY_EMPTY_ELEMENTDATA = {};

    /**
     * 数组被允许分配的最大长度，超过该长度可能导致OutOfMemeory
     */
    private static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8;

    /**
     * 属性表底层容器，数组
     */
    transient Object[] elementData;

    /**
     * 顺序表大小
     */
    private int size;

    /**
     * 空参构造
     */
    public SequenceList() {
        this.elementData = DEFAULTCAPACITY_EMPTY_ELEMENTDATA;
    }

    /**
     * 指定容量
     * @param initialCapacity   初始容量
     * @throws IllegalArgumentException 初始容量负数抛出该类型异常
     */
    public SequenceList(int initialCapacity) {
        if (initialCapacity < 0) {
            throw new IllegalArgumentException("Illegal Capacity: "+
                    initialCapacity);
        } else if (initialCapacity == 0) {
            this.elementData = EMPTY_ELEMENTDATA;
        } else {
            this.elementData = new Object[initialCapacity];
        }
    }

    /**
     * 清空顺序表
     */
    public void clear() {
        if (this.size > 0) {
            for (int i = 0; i < this.size; i++) {
                this.elementData[i] = null;
            }
            this.size = 0;
        }
    }

    /**
     * 判断顺序表是否为空
     * @return          true如果顺序表为空;否则false
     */
    public boolean isEmpty() {
        return this.size == 0;
    }

    /**
     * 获取顺序表大小
     * @return      顺序表大小
     */
    public int size() { return this.size; }

    /**
     * 插入元素
     * @param e     插入顺序表的元素
     */
    public boolean add(E e) {
        // 确保顺序表有足够的容量
        ensureCapacityInternal(this.size + 1);
        // 默认末尾插入
        this.elementData[size++] = e;
        return true;
    }


    private void ensureCapacityInternal(int minCapacity) {
        if (this.elementData == DEFAULTCAPACITY_EMPTY_ELEMENTDATA) {
            minCapacity = Math.max(DEFAULT_CAPACITY, minCapacity);
        }

        ensureExplicitCapacity(minCapacity);
    }

    private void ensureExplicitCapacity(int minCapacity) {
        if (minCapacity - this.elementData.length > 0) {
            grow(minCapacity);
        }
    }

    /**
     * 扩容，确保属性表能存储参数指定的最小容量的元素
     * @param minCapacity       最小容量
     */
    private void grow(int minCapacity) {
        int oldCapacity = this.elementData.length;
        int newCapacity = oldCapacity + (oldCapacity >> 1);
        if (newCapacity - minCapacity < 0) {
            newCapacity = minCapacity;
        }
        if (newCapacity - MAX_ARRAY_SIZE > 0) {
            newCapacity = hugeCapacity(minCapacity);
        }
        this.elementData = Arrays.copyOf(this.elementData, newCapacity);
    }

    private int hugeCapacity(int minCapacity) {
        if (minCapacity < 0) {
            throw new OutOfMemoryError();
        }
        return (minCapacity > MAX_ARRAY_SIZE) ?
                Integer.MAX_VALUE :
                MAX_ARRAY_SIZE;
    }

    /**
     * 在指定索引处插入元素
     * @param index     插入位置
     * @param e         目标元素
     */
    public void add(int index, E e) {
        // 索引index检测
        rangeCheckForAdd(index);

        // 容量检测
        ensureCapacityInternal(this.size + 1);
        // 元素后移
        System.arraycopy(this.elementData, index, this.elementData, index + 1, size - index);
        // 元素插入
        this.elementData[index] = e;
        size++;
    }

    private void rangeCheckForAdd(int index) {
        if (index < 0 || index > size) {
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }
    }

    private String outOfBoundsMsg(int index) {
        return "Index: "+index+", Size: "+size;
    }

    /**
     * 删除指定索引处元素
     * @param index     目标元素索引
     * @return          待删除元素
     */
    public E remove(int index) {
        // 检测索引index
        rangeCheck(index);
        // 元素存在，保存要删除元素
        E oldValue = elementData(index);
        // 目标元素之后的元素前移
        int numMoved = size - index - 1;
        if (numMoved > 0) {
            System.arraycopy(elementData, index+1, elementData, index,
                    numMoved);
        }
        // 源数组最后一个索引位置元素置空，元素大小减1
        this.elementData[--this.size] = null;
        return oldValue;
    }

    private void rangeCheck(int index) {
        if (index >= size || index < 0) {
            throw new IndexOutOfBoundsException(outOfBoundsMsg(index));
        }
    }

    E elementData(int index) {
        return (E) elementData[index];
    }

    /**
     * 删除某一元素
     * @param o
     * @return
     */
    public boolean remove(Object o) {
        // 查找元素
        if (null == o) {
            // o是null
            for (int i = 0; i < this.size; i++) {
                if (null == this.elementData[i]){
                    fastRemove(i);
                    return true;
                }
            }
        } else {
            // o不是null
            for (int i = 0; i < this.size; i++) {
                if (o.equals(this.elementData[i])){
                    fastRemove(i);
                    return true;
                }
            }
        }
        return false;
    }

    private void fastRemove(int index) {
        int numMoved = size - index - 1;
        if (numMoved > 0) {
            System.arraycopy(this.elementData, index + 1, this.elementData, index, numMoved);
        }
        this.elementData[--size] = null;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("[");
        for (int i = 0; i < this.size; i++) {
            if (i == this.size - 1) {
                sb.append(this.elementData[i]);
            } else {
                sb.append(this.elementData[i]).append(", ");
            }
        }
        sb.append("]");
        return sb.toString();
    }

    public Iterator<E> iterator() {
        return new Itr();
    }

    /**
     * An optimized version of AbstractList.Itr
     */
    private class Itr implements Iterator<E> {
        int cursor;       // index of next element to return
        int lastRet = -1; // index of last element returned; -1 if no such

        @Override
        public boolean hasNext() {
            return cursor != size;
        }

        @Override
        @SuppressWarnings("unchecked")
        public E next() {
            int i = cursor;
            if (i >= size) {
                throw new NoSuchElementException();
            }
            Object[] elementData = SequenceList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            cursor = i + 1;
            return (E) elementData[lastRet = i];
        }

        @Override
        public void remove() {
            if (lastRet < 0) {
                throw new IllegalStateException();
            }

            try {
                SequenceList.this.remove(lastRet);
                cursor = lastRet;
                lastRet = -1;
            } catch (IndexOutOfBoundsException ex) {
                throw new ConcurrentModificationException();
            }
        }

        @Override
        @SuppressWarnings("unchecked")
        public void forEachRemaining(Consumer<? super E> consumer) {
            Objects.requireNonNull(consumer);
            final int size = SequenceList.this.size;
            int i = cursor;
            if (i >= size) {
                return;
            }
            final Object[] elementData = SequenceList.this.elementData;
            if (i >= elementData.length) {
                throw new ConcurrentModificationException();
            }
            while (i != size ) {
                consumer.accept((E) elementData[i++]);
            }
            // update once at end of iteration to reduce heap write traffic
            cursor = i;
            lastRet = i - 1;
        }
    }
}
